/**
 * 监控配置管理器
 * 负责配置的初始化、更新和管理
 */

import type { MonitorConfig } from '~/types/monitor';

export class ConfigManager {
  private static instance: ConfigManager;
  private config: MonitorConfig;
  private listeners: Array<(config: MonitorConfig) => void> = [];

  private constructor() {
    this.config = this.initConfig();
  }

  static getInstance(): ConfigManager {
    if (!ConfigManager.instance) {
      ConfigManager.instance = new ConfigManager();
    }
    return ConfigManager.instance;
  }

  /**
   * 初始化配置
   */
  private initConfig(): MonitorConfig {
    const currentHost = window.location.host;
    const isLocalhost = currentHost.includes('localhost');
    const isTestEnv = currentHost.includes('box') || currentHost.includes('qc');

    // 设置项目名称
    const projectName =
      isTestEnv || isLocalhost ? 'nuxt-liveconsult-test' : 'nuxt-liveconsult';

    // 设置上报服务器地址
    const reportHost = window.location.protocol.includes('https')
      ? 'cn-hangzhou.log.aliyuncs.com'
      : 'cn-hangzhou.sls.aliyuncs.com';

    // 构建完整的上报URL
    const reportUrl = `${window.location.protocol}//${projectName}.${reportHost}/logstores/frontend/track?APIVersion=0.6.0`;

    return {
      projectName,
      reportHost,
      reportUrl,
      enableConsoleLog: process.env.NODE_ENV === 'development',
      enableReport: process.env.NODE_ENV === 'production',
      // 新增配置项
      maxCacheSize: 50, // 最大缓存数量
      batchSize: 10, // 批量上报大小
      flushInterval: 5000, // 上报间隔(ms)
      sampleRate: 1.0, // 采样率
      maxRetries: 3, // 最大重试次数
      retryDelay: 1000, // 重试延迟(ms)
      enablePerformanceMonitor: true,
      enableErrorMonitor: true,
      enableUserBehavior: false,
    };
  }

  /**
   * 获取配置
   */
  getConfig(): MonitorConfig {
    return { ...this.config };
  }

  /**
   * 更新配置
   */
  updateConfig(newConfig: Partial<MonitorConfig>): void {
    this.config = { ...this.config, ...newConfig };
    this.notifyListeners();
  }

  /**
   * 监听配置变化
   */
  onConfigChange(listener: (config: MonitorConfig) => void): () => void {
    this.listeners.push(listener);
    return () => {
      const index = this.listeners.indexOf(listener);
      if (index > -1) {
        this.listeners.splice(index, 1);
      }
    };
  }

  /**
   * 通知监听器
   */
  private notifyListeners(): void {
    this.listeners.forEach(listener => {
      try {
        listener(this.config);
      } catch (error) {
        console.warn('配置变化监听器执行失败:', error);
      }
    });
  }

  /**
   * 检查是否应该采样
   */
  shouldSample(): boolean {
    return Math.random() < this.config.sampleRate;
  }
}
